from flask import Flask
from flask import request
import json

from models.game import Game
from models.review import Review

# TODO(austin): Integrate SQLite3 database, use real game data
# TODO(austin): Add GET /games/$id/download endpoint

# Initialize app
app = Flask(__name__)


# GET /
# Returns a list of available endpoints
@app.route("/")
def get_home():
    return json.dumps(
        {
            'games_url': '/games'
        }
    )


# GET /games
# Returns a list of available games
@app.route("/games")
def get_games():
    games = [game.getAttributes() for game in Game.getAll()]
    return json.dumps(games)


# GET /games/$id
# Returns information about a specific game
@app.route("/games/<int:game_id>")
def get_game(game_id):
        game = Game.getById(game_id)
        if game:
            return json.dumps(game.getAllAttributes())
        else:
            return json.dumps({"error": "Game not found!"})


# GET /games/$id
# Returns information about a specific game
@app.route("/games/<int:game_id>/download")
def get_game_download(game_id):
        game = Game.getById(game_id)
        if game:
            return app.send_static_file("gamesfordownload/%d/game.zip"
                                        % game.getId())
        else:
            return json.dumps({"error": "Game not found!"})


# GET /games/$id/reviews
# Returns reviews/ratings for a specific game
@app.route("/games/<int:game_id>/reviews", methods=["POST", "GET"])
def get_game_reviews(game_id):
    print("TEST")
    if request.method == "POST":
        reviewData = request.get_json(force=True)
        print(reviewData)
        review = Review.createFromJson(reviewData)
        Review.save(review)

    reviews = [review.getAttributes()
               for review in Review.getByGameId(game_id)]
    return json.dumps(reviews)

if __name__ == "__main__":
    # Run the app
    app.run(debug=True, host='0.0.0.0')
